<template>
  <div class="page">
    <el-pagination
      @size-change="SizeChange"
      @current-change="pagesize"
      @prev-click="prevpage"
      @next-click="nextpage"
      :current-page.sync="data.offset"
      background
      :page-sizes="limit"
      :page-size="data.size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="count"
    ></el-pagination>
  </div>
</template>

<script lang="ts" setup>
import { defineEmit, defineProps, reactive, watch } from "vue";
import type { PropType } from "vue";
const emit = defineEmit(['offSet','sizes'])

const props = defineProps({
  count:{
    type: Number,
    default: 0
  },
  limit:{
    type: Array as PropType<number[]>,
    default(){
      return [10, 20, 30, 50]
    }
  },
  fetch:{
    type: Function,
    default: ()=>{}
  },
  sizes:{
    type: Number,
    default: 10
  },
  offSet:{
    type: Number,
    default: 1
  },
})

const data = reactive({
  offset: props.offSet, // 从第一页开始
  size: props.sizes,
  limit: props.limit
})

// 监听页码的变化
watch(()=> props.offSet, (n:number)=>{
  data.offset = n;
})

watch(()=> props.limit, (n:number[])=>{
  data.limit = n;
})

watch(()=> props.sizes, (n:number)=>{
  data.size = n;
})

// 拿到每页的页码
const SizeChange = (e:number) => {
  data.size = e;
  if(data.size * data.offset > props.count){
    let offset = Math.floor(props.count / data.size)
    props.fetch(data.size, offset == 0 ? 1 : offset);
    emit('offSet', offset);
  }else{
    props.fetch(data.size, data.offset);
    emit('offSet', data.offset);
  }
  emit('sizes', data.size);
  
}

// 下一页
const nextpage = (e:number)=> {
  data.offset = e;
  props.fetch(data.size, data.offset);
  emit('offSet', data.offset);
  emit('sizes', data.size);
}

// 上一页
const prevpage = (e:number)=> {
  data.offset = e;
  props.fetch(data.size, data.offset);
  emit('offSet', data.offset);
  emit('sizes', data.size);
}

// 选择页码分页
const pagesize = (e:number)=> {
  data.offset = e;
  props.fetch(data.size, data.offset);
  emit('offSet', data.offset);
  emit('sizes', data.size);
}
</script>

<style lang="scss" scoped>
.page {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  padding: 10px 0px;
}
</style>
